package com.binance.healthcenter.service;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

@Log4j2
@Service
public class DiscoveryClientService {
    @Autowired
    private DiscoveryClient discoveryClient;

    /**
     * 获取所有的服务名
     */
    public List<String> getServiceNameList() {
        log.info("DiscoveryClientService.getServiceNameList");
        List<String> serviceNameList = discoveryClient.getServices();
        return serviceNameList;
    }

    /**
     * 获取某个服务下面的所有实例
     */
    public List<ServiceInstance> getServiceInstanceList(String serviceName) {
        log.info("DiscoveryClientService.getServiceInstanceList:serviceName={}",serviceName);
        List<ServiceInstance> serviceInstanceList = discoveryClient.getInstances(serviceName);
        return serviceInstanceList;
    }

    /**
     * 判断某个服务是否在服务列表里
     */
    public Boolean isExistInEureka(String serviceName) {
        List<String> serviceNameList = getServiceNameList();
        return serviceNameList.contains(serviceName);
    }

    /**
     * 获取某个服务下面的所有实例
     */
    public List<ServiceInstance> getAllServiceInstanceList() {
        List<ServiceInstance> serviceInstanceList = Lists.newArrayList();
        List<String> serviceNameList = getServiceNameList();
        for (String serviceName : serviceNameList) {
            List<ServiceInstance> serviceInstances = getServiceInstanceList(serviceName);
            serviceInstanceList.addAll(serviceInstances);
        }
        return serviceInstanceList;
    }
    /**
     * 获取所有微服务的ip地址的set集合（为了调用cadvisor接口使用）
     * */
    public Set<String> getServiceHostSet() {
        List<ServiceInstance> serviceInstanceList = getAllServiceInstanceList();
        Set<String> serviceHostSet = Sets.newHashSet();
        for (ServiceInstance serviceInstance : serviceInstanceList) {
            serviceHostSet.add(serviceInstance.getHost());
        }
        return serviceHostSet;
    }


}
